package dt.bankAction;

import java.io.IOException;
import java.io.Reader;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.opensymphony.xwork2.ActionSupport;

import dt.member.memberVO;

public class InAction extends ActionSupport implements SessionAware {

	private Map session;
	public static Reader reader;
	public static SqlMapClient sqlMapper;
	
	private AccountVO paramClass;
	private AccountVO resultClass;
	private memberVO memClass;
	
	private static final long serialVersionUID = 1L;

	private String id;
	private int chargeMoney;
	private int chargeResult;
	
	public InAction() throws IOException {
		reader = Resources.getResourceAsReader("sqlMapConfig.xml"); //sqlMapConfig.xml �좎룞�쇿뜝�숈삕�좎룞���좎룞�쇿뜝�숈삕�좎룞�쇿뜝�숈삕�좎룞���좎룞�쇿뜝�숈삕�좎듅�먯삕.
		sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader); //sqlMapConfig.xml �좎룞�쇿뜝�숈삕�좎룞���좎룞�쇿뜝�숈삕�좑옙sqlMapper �좎룞�숈껜 �좎룞��
		reader.close();
	}
	
	public String form() {
		return SUCCESS;
	}
	
	public String execute() throws Exception {
		memClass = new memberVO();
		paramClass = new AccountVO();
		resultClass = new AccountVO();
		
		id = session.get("id").toString();
		memClass = (memberVO) sqlMapper.queryForObject("idCheck", id);
		
		if(memClass.getId() == null) {
			System.out.println("id가 존재 하지 않음");
			chargeResult = 0;
			return ERROR;
		}
		else {
			
			resultClass = (AccountVO)sqlMapper.queryForObject("account.select-account", memClass.getId());
			
			if(resultClass == null){
				System.out.println(memClass.getId());
				paramClass.setId(memClass.getId());
				paramClass.setTotal_money(chargeMoney);
				System.out.println(chargeMoney);
				sqlMapper.insert("account.insertCharge", paramClass);
				
				chargeResult = 1;
				return SUCCESS;
				
				
			} else {
			
				int totalMoney = resultClass.getTotal_money() + chargeMoney;
			
				paramClass.setId(id);
				paramClass.setTotal_money(totalMoney);
			
				sqlMapper.update("account.updateCharge", paramClass);
						
				chargeResult = 1;
				return SUCCESS;
			}
		}
				
	}

	@Override
	public void setSession(Map session) {
		this.session = session;
	}
	public Map getSession() {
		return session;
	}
	
	public void setChargeMoney(int chargeMoney){
		this.chargeMoney = chargeMoney;
	}
	public int getChargeMoney(){
		return chargeMoney;
	}
	
	public void setChargeResult(int chargeResult){
		this.chargeResult = chargeResult;
	}
	public int getChargeResult(){
		return chargeResult;
	}
}
